package com.example.workassignback.serviceImpl;

import com.example.workassignback.Mapper.UserMapper;
import com.example.workassignback.POJO.User;
import com.example.workassignback.serviceImpl.service.UserService;
import com.example.workassignback.utils.Result;
import com.example.workassignback.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private User user;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public Result userLogin(String cardId, String password) {
        User user = userMapper.loginCheck(cardId, password);
        try {
            //发放token
            String role = userMapper.selectRoleByUId(user.getUId());
            String token = tokenUtil.getToken(Integer.toString(user.getUId()), role);

            Map map = new HashMap<>();
            map.put("token", token);
            map.put("role", role);

            return Result.success(map);
        } catch (Exception e) {
            return Result.fail("登陆失败");

        }
    }

    @Override
    public Result userRegister(String cardId, String password, String phone, String name, String role) {

        if (cardId == null || cardId.length() != 18) {
            return Result.fail("注册失败");
        }

        User user = userMapper.selectUserByCardId(cardId);
        if (user == null) {
            user = new User();
            user.setName(name);
            user.setCardId(cardId);
            user.setPassword(password);
            user.setPhone(phone);

            // 提取出生日期部分
            String birthDateStr = cardId.substring(6, 14);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            LocalDate localDate = LocalDate.parse(birthDateStr, formatter);
            user.setBirthday(Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));

            // 提取性别码
            char genderCode = cardId.charAt(16);
            // 奇数为男性，偶数为女性
            user.setGender((genderCode % 2 == 0) ? true : false);

            userMapper.insertUser(user);


            System.out.println("user = " + user);
            if (role.equals("Doctor")) {
                userMapper.insertDoctor(user.getUId());
            } else {
                userMapper.insertPatient(user.getUId());
            }

            String token = tokenUtil.getToken(Integer.toString(user.getUId()), role);

            Map map = new HashMap<>();
            map.put("token", token);
            map.put("role", role);

            return Result.success(map);

        } else {
            return Result.fail("注册失败");
        }
    }
}